package mysql

import (
	"context"
	"fmt"
	"go.uber.org/zap"
	"gorm.io/gorm"
	log "maya-service/collector/logger"
	"maya-service/config"
	"maya-service/model"
	"maya-service/model/entity"
	"maya-service/utils"
)

var Option = &option{}

type option struct{}

func init() {
	Register(Option)
}

func (a *option) Init() {
	if config.Conf.AutoMigrate {
		p := &entity.Option{}
		if db.Migrator().HasTable(p) {
			log.Debug("table already exist: ", zap.String("table", p.TableName()))
			return
		}
		if err := db.AutoMigrate(p); err != nil {
			log.Error("filed to create table please check config or manually create", zap.String("table", p.TableName()), zap.String("err", err.Error()))
		} else {
			log.Info("create table successfully", zap.String("table", p.TableName()))
		}
	}
}

// Create
func (a *option) Create(ctx context.Context, m *entity.Option) (int64, error) {
	err := GetDB(ctx).Create(m).Error
	return m.Id, err
}

// Find detail
func (a *option) Find(ctx context.Context, in *model.OptionInfoRequest) (*entity.Option, error) {
	e := &entity.Option{}

	q := GetDB(ctx).Model(&entity.Option{})

	count := 0

	if in.Id > 0 {
		q = q.Where("id = ?", in.Id)
		count++
	}

	if in.TitleId > 0 {
		q = q.Where("title_id = ?", in.TitleId)
		count++
	}

	if in.Image != "" {
		q = q.Where("image = ?", in.Image)
		count++
	}

	if in.Desc != "" {
		q = q.Where("desc = ?", in.Desc)
		count++
	}

	if count == 0 {
		return e, nil
	}

	err := q.First(&e).Error
	return e, err
}

// Update
func (a *option) Update(ctx context.Context, id int64, dict map[string]interface{}) error {
	return GetDB(ctx).Model(&entity.Option{}).Where("id = ?", id).Updates(dict).Error
}

// Delete
func (a *option) Delete(ctx context.Context, in *model.OptionDeleteRequest) error {
	if in.Id > 0 {
		return GetDB(ctx).Delete(&entity.Option{}, in.Id).Error
	}

	if in.TitleId > 0 {
		return GetDB(ctx).Where("title_id = ?", in.TitleId).Delete(&entity.Option{}).Error
	}

	if len(in.TitleIds) > 0 {
		return GetDB(ctx).Where("title_id in ?", in.TitleIds).Delete(&entity.Option{}).Error
	}
	return fmt.Errorf("contion illegal")
}

// List query list
func (a *option) List(ctx context.Context, in *model.OptionListRequest) (int, []*entity.Option, error) {
	var (
		q       = GetDB(ctx).Model(&entity.Option{})
		err     error
		total   int64
		options []*entity.Option
	)

	if in.TitleId != nil {

		q = q.Where("title_id = ?", in.TitleId)

	}

	if len(in.TitleIds) > 0 {
		q = q.Where("title_id in ?", in.TitleIds)
	}

	if in.Image != nil {

		q = q.Where("image like ?", utils.SqlLike(in.Image))

	}

	if in.Desc != nil {

		q = q.Where("`desc` like ?", utils.SqlLike(in.Desc))

	}

	if in.CreatedAt != nil {

		q = q.Where("created_at = ?", in.CreatedAt)

	}

	if in.UpdatedAt != nil {

		q = q.Where("updated_at = ?", in.UpdatedAt)

	}

	if err = q.Count(&total).Error; err != nil {
		return 0, nil, err
	}
	if err = q.Order("id asc").Limit(in.Size).Offset((in.Index - 1) * in.Size).Find(&options).Error; err != nil {
		return 0, nil, err
	}
	return int(total), options, nil
}

// ExecTransaction execute database transaction
func (a *option) ExecTransaction(ctx context.Context, callback func(ctx context.Context) error) error {
	return GetDB(ctx).Transaction(func(tx *gorm.DB) error {
		ctx = context.WithValue(ctx, ContextTxKey, tx)
		return callback(ctx)
	})
}
